<!--
 * @Author: WuFeng <763467339@qq.com>
 * @Date: 2023-02-10 15:14:32
 * @LastEditTime: 2023-02-13 18:36:42
 * @LastEditors: WuFeng <763467339@qq.com>
 * @Description: 数据权限配置
 * @FilePath: \vue3-element-plus-web\src\views\SysManage\Resource\components\Drawer\dataAuth.vue
 * Copyright 版权声明
-->
<template>
  <div class="">
    <el-form
      :rules="rules"
      ref="dataForm"
      :model="temp"
      label-width="110px"
      style='width:100%;'
    >

      <el-form-item label="接口地址：" prop="apiPath">
        <el-input v-model="temp.apiPath" placeholder="请输入接口地址" clearable>
          <template #append>
            <el-button @click="getFieldList()">
              <el-icon><Search /></el-icon>
              获取字段
            </el-button>
          </template>
        </el-input>
      </el-form-item>

      <div class="modWrap">
        <div class="modWrap_left">
          <div class="modWrap_title">角色列表</div>
          <ul>
            <template v-for="(item, index) in roleList">
              <li v-if="item.id !== '1'" :key="index" :class="{active: item.id === temp.roleId}" @click="handleClickRole(item)">
                {{item.roleName}}
              </li>
            </template>
          </ul>
        </div>
        <div class="modWrap_right">

          <el-form-item label="mapperId：" prop="mapperId">
            <el-input v-model="temp.mapperId" placeholder="请输入mapperId" clearable></el-input>
          </el-form-item>

          <el-form-item label="权限范围：" prop="scopeType">
            <el-select
              v-model="temp.scopeType"
              placeholder="请选择权限范围"
              clearable
            >
              <el-option
                v-for="item in scopeTypeList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="指定对象：" prop="specifyType">
            <el-select
              v-model="temp.specifyType"
              placeholder="请选择指定对象"
              clearable
            >
              <el-option
                v-for="item in specifyTypeList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
            <el-input
              v-if="temp.specifyType !== '' && temp.specifyType !== 1"
              style="margin-top: 5px;"
              v-model="temp.targetId"
              placeholder="请输入指定对象"
              clearable
            >
            </el-input>
          </el-form-item>

          <div class="modWrap_title">接口字段</div>
          <el-table
            ref="tableList"
            :data="fieldList"
            v-loading="fieldListLoading"
            border
            fit
            highlight-current-row
            style="width: 100%;"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="50" align="center" />
            <!-- <el-table-column align="center" label="序号" width="60">
              <template v-slot="scope">
                <span>{{scope.$index + 1}}</span>
              </template>
            </el-table-column> -->
            <el-table-column label="字段名" prop="name"/>
            <el-table-column label="示例值" prop="value"/>
          </el-table>
        </div>
      </div>

    </el-form>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
// 图标组件
import { Search } from '@element-plus/icons-vue'
import request from '@/utils/request'
import { getDataScope } from '@/api/SysManage/resource.js'
import { getAllList } from '@/api/SysManage/role.js'

export default {
  name: 'Create',
  computed: {
    ...mapGetters([
      'drawerCurrent'
    ]),
    drawerType: function() {
      return this.drawerCurrent.drawerType
    }
  },
  components: {
    Search
  },
  data() {
    return {
      pageParams: {},
      temp: {
        roleId: '', // 角色id
        menuId: '', // 资源id
        mapperId: '', // mapperId
        scopeType: '', // 权限范围
        specifyType: '', // 指定对象 - 枚举值
        targetId: '', // 指定对象 - 部门id / 指定用户id （多个逗号隔开）
        columns: '' // 勾选列 的key （多个逗号隔开）
      },
      rules: {
        apiPath: [
          { required: true, message: '请输入接口地址', trigger: 'change' }
        ],
        scopeType: [
          { required: true, message: '请选择权限范围', trigger: 'change' }
        ],
        specifyType: [
          { required: true, message: '请选择指定对象', trigger: 'change' }
        ],
        mapperId: [
          { required: true, message: '请输入资源编号', trigger: 'change' },
          { max: 200, message: 'mapperId最大长度20位', trigger: 'change' }
        ]
      },
      // 权限范围枚举
      scopeTypeList: [
        {
          label: '所有人',
          value: 1
        },
        {
          label: '仅本人',
          value: 2
        },
        {
          label: '所在机构',
          value: 3
        },
        {
          label: '所在机构及子级',
          value: 4
        }
      ],
      // 指定范围枚举
      specifyTypeList: [
        {
          label: '不指定',
          value: 1
        },
        {
          label: '指定部门',
          value: 5
        },
        {
          label: '指定用户',
          value: 6
        }
      ],
      // 接口字段列表
      fieldList: [],
      // 多选选中的字段列表
      mulitipleFieldList: [],
      // 获取接口字段状态
      fieldListLoading: false,
      // 角色列表
      roleList: []
    }
  },
  watch: {
    // 表单内容体
    temp: {
      handler: function(val, oldVal) {
      },
      deep: true
    }
  },
  created() {
    // 列表传过来的数据
    this.pageParams = this.drawerCurrent.params.pageParams || {}
    const { code, id } = this.pageParams
    if (code !== '') {
      this.temp.apiPath = `/${code}/page`
      this.temp.menuId = id
    }
    // drawer loadding 状态 打开
    this.$store.dispatch('SetDrawerloading', true)
    // 获取角色列表
    this.getRoleList()
    // 获取字段列表
    this.getFieldList()
    // drawer loadding 状态 关闭
    this.$store.dispatch('SetDrawerloading', false)
  },
  mounted() {
  },
  methods: {
    // 点击角色
    handleClickRole(row) {
      const { id } = row
      this.temp.roleId = id
      // 获取数据权限配置
      this.getDataScope()
    },
    // 字段多选
    handleSelectionChange(val) {
      this.mulitipleFieldList = val
    },
    // 获取角色列表
    async getRoleList() {
      const res = await getAllList()
      this.roleList = (res.data && res.data.records) ? res.data.records : []
    },
    // 获取字段列表
    async getFieldList() {
      try {
        const res = await request({
          url: this.temp.apiPath,
          method: 'get',
          params: {}
        })
        const resData = (res.data && res.data.records) ? res.data.records : []
        let fieldListTemp = []
        if (resData.length > 0) {
          fieldListTemp = resData[0]
        }
        if (typeof fieldListTemp === 'object') {
          this.fieldList = []
          for (const item in fieldListTemp) {
            this.fieldList.push({
              name: item,
              value: fieldListTemp[item]
            })
          }
        }
        if (this.temp.roleId !== '') {
          // 获取数据权限配置
          this.getDataScope()
        }
      } catch (error) {
        this.$notify({
          title: '异常提示',
          message: '接口不存在',
          type: 'error',
          duration: 2000
        })
      }
    },
    // 获取数据权限配置
    async getDataScope() {
      try {
        const res = await getDataScope({
          roleId: this.temp.roleId,
          menuId: this.pageParams.id
        })
        const resData = res.data || {}
        // mapperId
        this.temp.mapperId = resData.mapperId || ''
        // 权限范围
        this.temp.scopeType = resData.scopeType || ''
        // 指定对象 - 枚举值
        this.temp.specifyType = resData.specifyType || ''
        // 指定对象 - 部门id / 指定用户id （多个逗号隔开）
        this.temp.targetId = resData.targetId || ''
        // 勾选列 的key （多个逗号隔开）
        this.temp.columns = resData.columns || ''
        if (this.temp.columns !== '') {
          const columnsTempArr = this.temp.columns.split(',')
          this.$refs.tableList.clearSelection()
          for (const item of this.fieldList) {
            if (columnsTempArr.indexOf(item.name) > -1) {
              this.$refs.tableList.toggleRowSelection(item)
            }
          }
        }
      } catch (error) {
        this.temp.mapperId = ''
        this.temp.scopeType = ''
        this.temp.specifyType = ''
        this.temp.targetId = ''
        this.temp.columns = ''
        this.$refs.tableList.clearSelection()
      }
    },
    // 提交表单
    submitForm() {
      return this.$refs['dataForm'].validate()
    },
    // 获取表单数据
    getFormData() {
      this.temp.columns = ''
      const columnsTempArr = []
      for (const item of this.mulitipleFieldList) {
        columnsTempArr.push(item.name)
      }
      this.temp.columns = columnsTempArr.toString()
      return this.temp
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.modWrap{
  display: flex;
  &_title{
    font-weight: bold;
    font-size: 14px;
    margin-bottom: 10px;
  }
  &_left,&_right{

  }
  &_left{
    width: 220px;
    padding-right: 15px;
    ul{
      margin: 0;
      padding: 0;
      li{
        list-style: none;
        cursor: pointer;
        font-size: 14px;
        background-color: #f1f1f1;
        margin: 5px 0;
        border-radius: 5px;
        padding: 5px 10px;
      }
      li:hover{
        background-color: #e1f1f1;
      }
      li.active{
        background-color: #409eff;
        color: #fff;
      }
    }
  }
  &_right{
    flex: 1;
  }
}
.el-form-item__content{
  .el-select{
    flex: 1;
  }
}
</style>
